package net.zjitc.utils.dispacher;

import net.zjitc.utils.ControllerUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/8.
 */
//在此DispacherServlet里面去分配或调度到底是哪个类的什么方法
@WebServlet(name = "DispacherServlet",urlPatterns = "/")
public class DispacherServlet extends HttpServlet {
    Map<String,Method> urlMap=new HashMap();
    Map<Method,Object> methodMap=new HashMap();
    @Override
    public void init() throws ServletException {
     //1遍历net.zjitc.controller包下面的所有的Class对象
       String packName="net.zjitc.controller";
        try {
            List<Class> classes= ControllerUtils.getAllClass(packName);
            //2.找到类对象的所有的方法
            for(Class c:classes){
                Method[] methods = c.getMethods();
                for(Method m:methods){
                   //3.判断方法上面是否有注解，如果有注解，才把它们放在map集合中。
                   URLMapping annotation=m.getAnnotation(URLMapping.class);
                   if(annotation!=null){
                       String url=annotation.url();
                       urlMap.put(url,m);
                       Object o=c.newInstance();//实体类
                       methodMap.put(m,o);
                   }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 1遍历net.zjitc.controller包下面的所有的.class文件
         * 2.找到类对象中的所有的方法
         * 3.判断方法上面是否有注解，如果有注解，才把它们放在map集合中。
         */

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        String url= req.getServletPath();
        /**
         * net.zjitc.controller  ---java
         *
         * urlMap<url,method>
         * method<method,class>
         *     method.invoke(class,request,response)
         */

         //如果没有此servlet,则直接提示404
        if(!urlMap.containsKey(url)){
            resp.setStatus(404);
            return;
        }
        Method m=urlMap.get(url);
        Object o=methodMap.get(m);
        try {
            if(req.getMethod().equals("POST")){
                req.setCharacterEncoding("utf-8");
            }
           String str= (String) m.invoke(o,req,resp);
            if(str==null){
                return;
            }
           if(str!=null || (!"".equals(str))) {
               if (str.startsWith("Redirect:")) {
                   resp.sendRedirect(str.substring(9));
               } else {
                   req.getRequestDispatcher(str).forward(req, resp);
               }
           }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
